import { Component, OnInit } from '@angular/core';
import { Router, NavigationExtras, ActivatedRoute } from '@angular/router';
import { ToastController } from '@ionic/angular';
import {HttpClient,HttpHeaders} from "@angular/common/http";
import { Validators, FormBuilder, ValidationErrors, AbstractControl, FormGroup, FormControl } from '@angular/forms';
import { CommonResponse,VerificationType,ToastColor,CommonService,AppParam } from '@services/common-service.service';
import { AuthTokenService } from '@services/auth-token.service';
import {environment} from 'src/environments/environment';
// import { EventEmitterService,EventName } from '@services/event-emitter.service';
import {TranslateService} from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';
import { EncryptService } from '@services/encrypt.service';
@Component({
  selector: 'app-password-reset',
  templateUrl: './password-reset.page.html',
  styleUrls: ['./password-reset.page.scss'],
})
export class PasswordResetPage implements OnInit {
  title='Send the verification code to your mobile number';
  public seconds:number = 10;
  public sendView:boolean = false;
  resetPwdForm!: FormGroup
  public defaultSmsCountDown:number;
  i18n:any;
  backUrl:string = '/tabs/myAccount/setting/payment-settings/payment-password';
  constructor(
    private router:Router,
    private http:HttpClient,
    private toastController: ToastController,
    private fb: FormBuilder,
    private authTokenService: AuthTokenService,
    private translate: TranslateService,
    private defaultLanguageService:DefaultLanguageService,
    private encryptService:EncryptService,
    private commonService:CommonService,
    private activatedRoute:ActivatedRoute
  ) { 
    let defultLanguage = this.defaultLanguageService.getDefaultLanguage();
    this.translate.setDefaultLang(defultLanguage);
    this.translate.use(defultLanguage);
    this.translate.get('myAccount.setting.payment_settings.password_setting').subscribe((value)=>{
      this.i18n = value;
    });

    this.resetPwdForm = this.fb.group({
      code:[null,[Validators.required]]
    });

    this.defaultSmsCountDown = parseInt(this.commonService.getAppParamFromCache(AppParam.SMS_COUNT_DOWN));
    this.seconds = this.defaultSmsCountDown;

    this.activatedRoute.queryParams.subscribe((data)=>{
      if(data.url){
        this.backUrl=data.url;
      }
    });
  }
  appUserId = this.authTokenService.getAppUserId();
  ngOnInit() {
    this.sendVerificationCode();
  }

  toNext(){
    let currentTime = new Date().getTime();
    let sign1 = this.encryptService.md5Ecrypt(this.appUserId+this.authTokenService.getDeviceId()+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(this.appUserId+","+this.authTokenService.getDeviceId()+","+currentTime);
    const httpOptions = {
      headers: new HttpHeaders({'Content-Type':'application/json','sign1':sign1,'sign2':sign2 })
    };

    var api = "/scm/app/checkAppVerificationCode.do";
    var requestJson = {
      'appUserId':this.appUserId,
      'verificationCode':this.resetPwdForm.value.code,
      "verificationType":VerificationType.RESET_PAYMENT_PASSWORD
    }
    this.http.post(api,requestJson,httpOptions).subscribe((response:CommonResponse) => {
      if(response.isSuccess && response.responseBody.isPass){
        let navigationExtras: NavigationExtras = {
          queryParams: { 
           appUserId: this.appUserId,
           resetPwd:true,
           pageTitle :this.i18n.reset_page_title,
           formTitle :this.i18n.reset_password_title,
           url:this.backUrl
        }
        };
        this.router.navigate(['/tabs/myAccount/setting/payment-settings/payment-password'], navigationExtras);
      }else{
        this.commonService.commonToast(ToastColor.warning,'verification failed');
      }
    },(errorResponse)=>{
      this.commonService.commonToast(ToastColor.warning,'verification failed');
    });
    // let navigationExtras: NavigationExtras = {
    //   queryParams: {}
    // };
  
  }

  sendVerificationCode(){
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };
    var api = "/scm/app/sendAppVerificationCode.do";
    var requestJson = {
      'appUserId':this.appUserId,
      'appCode':environment.APP_CODE,
      'deviceId':this.authTokenService.getDeviceId(),
      'verificationType':VerificationType.RESET_PAYMENT_PASSWORD
    }
    this.http.post(api,requestJson,httpOptions).subscribe((response) => {
      this.countDown();
    },(errorResponse)=>{
      this.toastController.create({
        message:errorResponse.error.errorMsg,
        duration: 2000,
        color:'warning',
        position:'top'
      }).then(toast=>{
        toast.present();
      });
    });
  }

  countDown(){
    this.sendView = true;
    var id = setInterval(() => {
      this.seconds--;
      if(this.seconds == 0){
        this.seconds = this.defaultSmsCountDown;
        clearInterval(id);
        this.sendView = false;
      }
    }, 1000);
  }
}
